"ui";
importClass(android.Manifest);

importClass(android.os.Environment);
importClass(android.os.Build);
let androidx = Packages.androidx;
importClass(android.net.Uri)
importClass(android.provider.DocumentsContract)
importClass(androidx.documentfile.provider.DocumentFile)
//importClass(android.support.v4.provider.DocumentFile)
importClass(java.nio.ByteBuffer)



function SystemFileManagement() {
    function SystemFileManagement() {
        this.ResultIntent = this.SystemResultIntent();
        //初始化监听
        this.ResultIntent.init();
    }
    //接收信息
    SystemFileManagement.prototype.SystemResultIntent = function() {
        return {
            intentCallback: {
                REQUEST_CODE_FOR_DIR: null
            },
            init: function() {
                activity.getEventEmitter().on("activity_result", (requestCode, resultCode, data) => {
                    this.onActivityResult(requestCode, resultCode, data);
                });
            },
            startActivityForResult: function(intent, callback) {
                var i;
                for (i = 0; i < 65536; i++) {
                    if (!(i in this.intentCallback)) break;
                }
                if (i >= 65536) {
                    toast("启动Intent失败：同时请求的Intent过多");
                    return;
                }
                this.intentCallback[i] = callback;
                REQUEST_CODE_FOR_DIR = i;
                activity.startActivityForResult(intent, i);
            },
            onActivityResult: function(requestCode, resultCode, data) {
                var cb = this.intentCallback[requestCode];
                if (!cb) return;
                delete this.intentCallback[requestCode];
                cb(requestCode, resultCode, data);
            }
        };
    }
    //链接转换
    SystemFileManagement.prototype.PathToUri = function(path) {
        return Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" + path.replace("/storage/emulated/0/", "").replace("/", "%2F"));
    }
    //获得访问data权限
    SystemFileManagement.prototype.PermissionDeclaration = function(fun) {
        var uri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata");
        var documentFile = DocumentFile.fromTreeUri(activity, uri);
        var intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION |
            Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION |
            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, documentFile.getUri());
        //activity.startActivityForResult(intent, 8000);
        this.ResultIntent.startActivityForResult(intent, function(requestCode, resultCode, data) {
            //if (resultCode != activity.RESULT_OK) return;
            if (data == null) {
                return;
            }
            var url = null;
            if ((uri = data.getData()) != null) {
                activity.getContentResolver().takePersistableUriPermission(uri, data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION)); //保存目录的访问权限
            }
        });
    }
    //URL转换
    SystemFileManagement.prototype.PathToUri = function(path) {
        return Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" + path.replace("/storage/emulated/0/", "").replace("/", "%2F"));
    }

    //使用系统文件管理选择文件
    SystemFileManagement.prototype.OpenPath = function(Path, FileType, fun) {
        var path = AltText(Path, '/', '%2f');
        var uri = Uri.parse("content://com.android.externalstorage.documents/document/primary:" + path);
        var intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType(FileType); //想要展示的文件类型
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri);
        //app.startActivity(intent);
        this.ResultIntent.startActivityForResult(intent, function(requestCode, resultCode, data) {
            if (resultCode != activity.RESULT_OK) return;
            fun(new SystemFileManagement().URIUtils_uriToFile(data.getData()));
        });
    }
    //转换文件路径
    SystemFileManagement.prototype.URIUtils_uriToFile = function(uri) { //Source : https://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
        var r = null,
            cursor, column_index, selection = null,
            selectionArgs = null,
            isKitKat = android.os.Build.VERSION.SDK_INT >= 19,
            docs;
        if (uri.getScheme().equalsIgnoreCase("content")) {
            if (isKitKat && android.provider.DocumentsContract.isDocumentUri(activity, uri)) {
                if (String(uri.getAuthority()) == "com.android.externalstorage.documents") {
                    docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
                    if (docs[0] == "primary") {
                        return android.os.Environment.getExternalStorageDirectory() + "/" + docs[1];
                    }
                } else if (String(uri.getAuthority()) == "com.android.providers.downloads.documents") {
                    uri = android.content.ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        parseInt(android.provider.DocumentsContract.getDocumentId(uri))
                    );
                } else if (String(uri.getAuthority()) == "com.android.providers.media.documents") {
                    docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
                    if (docs[0] == "image") {
                        uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if (docs[0] == "video") {
                        uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if (docs[0] == "audio") {
                        uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    selection = "_id=?";
                    selectionArgs = [docs[1]];
                }
            }
            try {
                cursor = activity.getContentResolver().query(uri, ["_data"], selection, selectionArgs, null);
                if (cursor && cursor.moveToFirst()) {
                    r = String(cursor.getString(cursor.getColumnIndexOrThrow("_data")));
                }
            } catch (e) {
                log(e)
            }
            if (cursor) cursor.close();
            return r;
        } else if (uri.getScheme().equalsIgnoreCase("file")) {
            return String(uri.getPath());
        }
        return null;
    }
    return new SystemFileManagement;
}
//替换字符串
function AltText(max, may, maz) {
    var tun = max.split(may).join(maz);
    return tun;
}



var FileManagement = new SystemFileManagement();
//获得data访问权限
FileManagement.PermissionDeclaration();
/*
//使用系统文件管理器选择文件并返回路径---非阻塞回调
FileManagement.OpenPath("/脚本/", "text/*", function(FilePath) {
    log(FilePath)
});
*/
//log(context.checkSelfPermission)



/*
类型介绍

image/jpeg
audio/mpeg4-generic
text/html
audio/mpeg
audio/aac
audio/wav
audio/ogg
audio/midi
audio/x-ms-wma
video/mp4
video/x-msvideo
video/x-ms-wmv
image/png
image/jpeg
image/gif
.xml ->text/xml
.txt -> text/plain
.cfg -> text/plain
.csv -> text/plain
.conf -> text/plain
.rc -> text/plain
.htm -> text/html
.html -> text/html
.pdf -> application/pdf
.apk -> application/vnd.android.package-archive
DOC = “application/msword”
DOCX = “application/vnd.openxmlformats-officedocument.wordprocessingml.document”
XLS = “application/vnd.ms-excel application/x-excel”;
XLSX = “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”;
PPT = “application/vnd.ms-powerpoint”;
PPTX = “application/vnd.openxmlformats-officedocument.presentationml.presentation”;

.doc application/msword
.dot application/msword

.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12

.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel

.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12

.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint

.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12
.mdb application/vnd.ms-access
前往
http://t.csdn.cn/io6sX
*/

